package come.itheima.springbootwebmybatistlias.filter;


import com.alibaba.fastjson.JSONObject;
import come.itheima.springbootwebmybatistlias.pojo.Result;
import come.itheima.springbootwebmybatistlias.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取请求url
        String url = req.getRequestURI().toString();
        log.info("请求的url{}",url);


        //判断请求url是否包含Login，若包含则是登陆操作，放行
        if (url.contains("login")){
            log.info("这是登陆操作");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //获取请求头的令牌
        String jwt = req.getHeader("token");

        //判断令牌是否存在，若不存在，返回错误结果
        if (!StringUtils.hasLength(jwt)){//判断是否为空字符串
            log.info("请求头为空");
            Result error = Result.error("NOT_LOGIN");
            //手动转换 对象->json ----------->阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;

        }

        //解析令牌，若失败则返回错误结果
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {//jwt解析失败
            e.printStackTrace();
            log.info("解析令牌失败");
            Result error = Result.error("NOT_LOGIN");
            //手动转换 对象->json ----------->阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        //放行
        log.info("令牌合法");
        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
